import React, { useRef, useState, useEffect } from 'react';
import { Tabs } from 'antd';
import { Link, Outlet, useLocation, useNavigate } from 'react-router-dom';
import { menuList } from '../config/menuList';
import ComBreadcrumb from './ComBreadcrumb';


type TargetKey = React.MouseEvent | React.KeyboardEvent | string;

const ComTabs: React.FC = () => {
    const [activeKey, setActiveKey] = useState('/home');
    const [items, setItems] = useState([
        {
            label: '首页',
            children: <div>
                <ComBreadcrumb></ComBreadcrumb>
                <Outlet></Outlet>
            </div>,
            key: '/home',
            closable: false
        },
    ]);

    const navigata = useNavigate()


    const onChange = (e: string) => {
        setActiveKey(e);
        navigata(e)
    };

    //跳转路由的转换
    useEffect(() => {
        const pathArr = location.pathname.split('/').slice(1)
        let count = 0
        let arr: any = []
        const checkLise = (list: any) => {
            list.forEach((p: any) => {
                if (pathArr[count] == p.key) {
                    if (p.children) {
                        count++
                        checkLise(p.children)
                        arr.unshift(p.label)
                    } else {
                        arr.unshift(p.label)
                    }
                }
            })
        }
        checkLise(menuList)
        // //当前tab标签名
        const checkItem = arr[arr.length - 1]
        const res = items.some(i => i.label == checkItem)
        if (!res) {
            setItems([
                ...items,
                {
                    label: checkItem,
                    children:
                        <div>
                            <ComBreadcrumb></ComBreadcrumb>
                            <Outlet></Outlet>
                        </div>,
                    key: location.pathname,
                    closable: true
                }
            ])
        }
        setActiveKey(location.pathname);
    }, [location.pathname])



    const remove = (e: TargetKey) => {
        const arr = items
        const path = arr.splice(arr.findIndex(i => i.key == e), 1)
        setItems([...arr])
        console.log('path', arr, arr[arr.length - 1].key)
        setActiveKey(path[0].key);
        navigata(arr[arr.length - 1].key)
    };

    const onEdit = (targetKey: React.MouseEvent | React.KeyboardEvent | string, action: 'add' | 'remove',) => {
        if (action === 'add') {

        } else {
            remove(targetKey);
        }
    };

    return (
        <Tabs
            type="editable-card"
            onChange={onChange}
            activeKey={activeKey}
            onEdit={onEdit}
            hideAdd={true}
            items={items}
        />
    );
};

export default ComTabs;